package com.tiecode.plugin.regex.editor;

import com.tiecode.develop.component.widget.editor.highlight.DecisionBaseAnalyzer;
import com.tiecode.plugin.regex.editor.decision.RegexDecision;
import com.tiecode.plugin.regex.editor.decision.State;

import java.io.IOException;
import io.github.scave.lsp4a.highlight.token.IdentifierToken;
import io.github.scave.lsp4a.highlight.token.IdentifierTokenizer;
import io.github.scave.lsp4a.highlight.token.TokenModel;

public class RegexAnalyzer extends DecisionBaseAnalyzer<State> {

    public RegexAnalyzer() {
        RegexDecision decision = new RegexDecision();
        addDecision(decision);
    }

    @Override
    public TokenModel getTokenModel(CharSequence content) {
        RegexDecision.clear();
        TokenModel head = null;
        TokenModel node = null;
        IdentifierTokenizer tokenizer = new IdentifierTokenizer(String.valueOf(content));
        try {
            while (true) {
                int token = tokenizer.yylex();
                if (token == IdentifierToken.EOF) {
                    break;
                }
                int line = tokenizer.yyline();
                int column = tokenizer.yycolumn();
                String text = tokenizer.yytext();
                if (node == null) {
                    node = new TokenModel(token, line, column, text);
                    head = node;
                } else {
                    TokenModel curr = node;
                    node =  new TokenModel(token, line, column, text);
                    curr.next = node;
                    node.prev = curr;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return head;
    }

    @Override
    public State getDecisionEnv() {
        return new State();
    }
}
